package com.rookieCi.qrcodefile.sync;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;

import com.rookieCi.qrcodefile.BuildConfig;
import com.rookieCi.qrcodefile.QrApp;
import com.rookieCi.qrcodefile.utils.Logger;
import com.rookieCi.qrcodefile.utils.UserConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SendFileContact {
    public static int codeLen;//默认 80;//单次发送的数据量

    static {
        codeLen = UserConfig.getSendNumb();
    }

    /**
     * 0-文件，1文本，2-压缩文件，3-压缩文本
     */
    private int sendType;
    private String text;//sendType=1时使用，最大长度100个字
    private int no;
    private String filePath;//文件路径
    private FileInputStream inputStream;//sendType=2时使用
    private OnFileContactInterface contactInterface;

    public SendFileContact(Intent intent, OnFileContactInterface contactInterface) {
        this.contactInterface = contactInterface;
        long l = System.currentTimeMillis();
        no = (int) (l % 10000);

        sendType = intent.getIntExtra("sendType", 0);
        if (sendType == 1) {
            text = intent.getStringExtra("text");
        } else if (sendType == 3) {
            text = intent.getStringExtra("text");
        } else if (sendType == 2) {
            filePath = intent.getStringExtra("text");
            if (contactInterface != null) {
                boolean b = contactInterface.checkFilePermissions();
                if (b) openFile();
            }
        } else if (intent.getAction().equals(Intent.ACTION_SEND)) {//文件
            Bundle bundle = intent.getExtras();
            if (bundle == null) return;
            Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
            if (uri == null) return;//content://media/external/file/50489
            filePath = getRealPathFromUri(QrApp.getInstance(), uri);
            if (contactInterface != null) {
                boolean b = contactInterface.checkFilePermissions();
                if (b) openFile();
            }
        }
    }

    /**
     * 打开文件
     */
    public void openFile() {
        if (TextUtils.isEmpty(filePath)) return;
        File file = new File(filePath);
        if (file.exists()) {
            try {
                inputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                if (BuildConfig.DEBUG) e.printStackTrace();
            }
        }
    }

    /**
     * @return true 打开文件成功
     */
    public boolean isOpenFile() {
        return inputStream != null;
    }

    public void onDestroy() {
        if (inputStream == null) return;
        try {
            inputStream.close();
        } catch (IOException e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            Logger.out("getRealPathFromUri: " + contentUri);
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if (cursor != null && cursor.getColumnCount() > 0) {
                cursor.moveToFirst();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String path = cursor.getString(column_index);
                Logger.out("getRealPathFromUri: column_index=" + column_index + ", path=" + path);
                return path;
            } else {
                Logger.out("getRealPathFromUri: invalid cursor=" + cursor + ", contentUri=" + contentUri);
            }
        } catch (Exception e) {
            Logger.out("" + e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    public int getSendType() {
        return sendType;
    }

    public int getNo() {
        return no;
    }

    private int codeInt;//-1表示结束
    private List<String> textList;//仅文本时使用

    public String getCodeString() {
        if (sendType == 1 || sendType == 3) {
            if (textList == null) {
                textList = new ArrayList<>();
                if (text != null && text.length() > codeLen) {
                    for (int i = 1; ; i++) {
                        int i1 = (i - 1) * codeLen;
                        int i2 = i1 + codeLen;
                        if (i2 > text.length()) {
                            String substring = text.substring(i1);
                            textList.add(substring);
                            break;
                        } else {
                            String substring = text.substring(i1, i2);
                            textList.add(substring);
                        }
                    }
                } else textList.add(text);
            }
            return textList.size() <= codeInt
                    ? null
                    : textList.get(codeInt);
        } else {//文件
            if (inputStream == null) return null;
            if (codeInt == 0) {//最开始将文件名发送过去
                File file = new File(filePath);
                return file.getName();
            }
            try {
                byte[] bytes = new byte[codeLen];
                int read = inputStream.read(bytes);
                if (read < 0) {//文件读取完成
                    inputStream.close();
                    inputStream = null;
                    return null;
                }
                String base64;
                if (read == bytes.length) {
                    base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
                    //String zip = ZipUtils.zip(bytes);
                    /*String zip = ZipUtils.gzip(bytes);
                    Logger.out("base64:" + base64);
                    Logger.out("zip:" + zip);
                    Logger.out("base64.len:" + base64.length() + " zip.len:" + zip.length());*/
                } else {
                    byte[] bs = Arrays.copyOf(bytes, read);
                    base64 = Base64.encodeToString(bs, Base64.DEFAULT);
                }
                return base64;
            } catch (IOException e) {
                if (BuildConfig.DEBUG) e.printStackTrace();
            }
            return null;
        }
    }

    public int getCodeInt() {
        return codeInt;
    }

    public void moveNext() {
        codeInt++;
    }
}
